// pages/app/user/myCerts/myCerts.js
const app = getApp();
const base64 = require('../../../../utils/base64.js')

var host = app.globalData.host;
var utils = app.globalData.utils;
var self = null;

Page({
  data: {
    themeColor: '',
    themeColor2: '',
    themeColor3: '',
    defaultColor: '',
    borderColor: '',
    list: [],
    pageNum: 1,
    pageSize: 0,
    totalPage: 0,
    companyName: ''
  },
  onLoad: function (options) {
    self = this;
    self.getStyle();
    self.init();
  },
  getStyle() {
    self.setData({
      themeColor: app.globalData.themeColor,
      themeColor2: app.globalData.themeColor2,
      themeColor3: app.globalData.themeColor3,
      defaultColor: app.globalData.defaultColor,
      borderColor: app.globalData.borderColor
    })
  },
  init() {
    var userInfo = app.globalData.userInfo;
    if (userInfo.companyId) {
      var url = host + '/lx/mini/user/companyInfo';
      var params = {
        id: userInfo.companyId
      };
      var success = function (res) {
        self.setData({
          companyName: res.info.englishName
        })
        self.getCerts();
      }
      var fail = function (res) {
        console.log(res);
      };
      var complete = function () { };
      utils.request(url, params, success, fail, complete);

    } else {
      self.getCerts();
    }
  },
  getCerts() {
    console.log(app.globalData.userInfo);
    var url = host + '/lx/mini/user/cert';
    var params = {
      page: 1
    };
    var success = function (res) {
      console.log(res);
      var list = res.info.list;
      for (var i = 0; i < list.length; i++) {
        // var postfix = "?watermark/3/text/{}/font/dGltZXMgbmV3IHJvbWFu/fontsize/2000/fill/IyM2NDY0NjQ=/dissolve/85/gravity/Center/dx/0/dy/-120/text/U3VwZXJsaW5rcGx1cw==/font/dGltZXMgbmV3IHJvbWFu/fontsize/2000/fill/IyM2NDY0NjQ=/dissolve/85/gravity/Center/dx/0/dy/130";
        var postfix = "?watermark/3/text/{}/fontsize/2000/fill/IyM2NDY0NjQ=/dissolve/85/gravity/Center/dx/0/dy/-120/text/{}/fontsize/2000/fill/IyM2NDY0NjQ=/dissolve/85/gravity/Center/dx/0/dy/180";
        var nameCode = base64.encode(app.globalData.userInfo.firstName + " " + app.globalData.userInfo.lastName);
        // var companyCode = 'U3VwZXJsaW5rcGx1cw==';
        var companyCode = self.data.companyName ? base64.encode(self.data.companyName) : 'U3VwZXJsaW5rcGx1cw==';
        nameCode = nameCode.replace(/\+/g, "-").replace(/\//g, "_");
        companyCode = companyCode.replace(/\+/g, "-").replace(/\//g, "_");
        postfix = postfix.replace("{}", nameCode);
        postfix = postfix.replace("{}", companyCode);
        list[i].image = list[i].image + postfix;
        // console.log(list[i].image)
      }
      self.setData({
        list: list,
        pageNum: res.info.pageNumber,
        pageSize: res.info.pageSize,
        totalPage: res.info.totalPage
      })
    }
    var fail = function (res) {
    };
    var complete = function () { };
    utils.request(url, params, success, fail, complete);
  },
  saveCert(event){
    wx.showModal({
      title: '提示',
      content: '是否要下载证书？',
      success(res) {
        if (res.confirm) {
          var img = event.currentTarget.dataset.cert
          img = img.replace("http://", "https://");

          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {

              wx.showLoading({
                title: '下载中…',
                mask: true
              })
              wx.downloadFile({
                url: img,
                success(res) {
                  const filePath = res.tempFilePath
                  // wx.openDocument({
                  //   filePath,
                  //   success(res) {
                  //     console.log('打开文档成功')
                  //   }
                  // })
                  wx.saveImageToPhotosAlbum({
                    filePath: filePath,
                    success(res) {
                      wx.hideLoading();
                      wx.showToast({
                        title: '成功保存至相册',
                        icon: 'none'
                      })
                    },
                    fail(res) {
                      console.log("保存失败");
                      console.log(res);
                      wx.hideLoading();
                    }
                  })
                },
                fail(res) {
                  console.log("下载失败");
                  console.log(res);
                  wx.hideLoading();
                }
              })
            },
            fail(res) {
              console.log("authorize fail");
              console.log(res);
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '没有保存图片到系统相册的权限',
                confirmText: '去设置',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting({
                    })
                  }
                }
              })
            }
          })

        } else if (res.cancel) {
          console.log('取消下载')
        }
      }
    })
  },
  base64_encode(str) { // 编码，配合encodeURIComponent使用
    var c1, c2, c3;
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var i = 0, len = str.length, strin = '';
    while(i <len) {
      c1 = str.charCodeAt(i++) & 0xff;
      if (i == len) {
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
        strin += "==";
        break;
      }
      c2 = str.charCodeAt(i++);
      if (i == len) {
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
        strin += "=";
        break;
      }
      c3 = str.charCodeAt(i++);
      strin += base64EncodeChars.charAt(c1 >> 2);
      strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
      strin += base64EncodeChars.charAt(c3 & 0x3F)
    }
    return strin
  }
})